package com.uestc.utils;


import java.io.IOException;

public class OpenSSLUtil {
    public static void main(String[] args) {
        String inputFile = "test.txt";
        String encryptedFile = "outputfile.aes";
        String decryptedFile = "decryptedfile.txt";

        String password = "123456";
        // 加密文件
        encryptFile(password, inputFile, encryptedFile);

        // 解密文件
        decryptFile(password, encryptedFile, decryptedFile);
    }


    public static void encryptFile(String password, String inputFile, String outputFile) {

        // 使用OpenSSL进行加密
        String encryptCommand = "openssl enc -aes-256-cbc -salt -in " + inputFile + " -out " + outputFile + " -pass pass:" + password;

        executeCommand(encryptCommand, "文件加密成功", "文件加密失败");

    }

    public static void decryptFile(String password, String inputFile, String outputFile) {
        // 使用OpenSSL进行解密
        String decryptCommand = "openssl enc -aes-256-cbc -d -in " + inputFile + " -out " + outputFile + " -pass pass:" + password;

        executeCommand(decryptCommand, "文件解密成功", "文件解密失败");

    }

    private static void executeCommand(String command, String successMessage, String failureMessage) {
        try {
            Process process = Runtime.getRuntime().exec(command);
            int exitCode = process.waitFor();
            if (exitCode == 0) {
                System.out.println(successMessage);
            } else {
                System.out.println(failureMessage);
            }
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}